<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- 引入 ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
    <!-- 页面的其他标签 -->
    <title>ECharts with AJAX in JSP</title>
    <script>
    使用这个xhr
        // 定义 AJAX 请求函数
        function fetchData(chartType, url, chartElementId) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var response = JSON.parse(xhr.responseText);
                    if (response.code === "0") {
                        // 使用获取的数据初始化图表
                        initChart(chartType, chartElementId, response.data);
                    }
                }
            };
            xhr.send();
        }

        // 定义图表初始化函数
        function initChart(chartType, chartElementId, data) {
            var myChart = echarts.init(document.getElementById(chartElementId));
            var option = null;

            if (chartType === 'line') {
                option = {
                    title: { text: 'Line Chart' },
                    xAxis: { type: 'category', data: data.categories },
                    yAxis: { type: 'value' },
                    series: [{ data: data.values, type: 'line' }]
                };
            } else if (chartType === 'bar') {
                // 根据图表类型设置不同的 ECharts 配置
                option = {
                        title: { text: 'Line Chart' },
                        xAxis: { type: 'category', data: data.categories },
                        yAxis: { type: 'value' },
                        series: [{ data: data.values, type: 'bar' }]
                    };
            } else if (chartType === 'pie') {
                option = {
                        title: { text: 'Line Chart' },
                        xAxis: { type: 'category', data: data.categories },
                        yAxis: { type: 'value' },
                        series: [{ data: data.values, type: 'pie' }]
                    };
            }

            myChart.setOption(option);
        }

        // 页面加载完成后执行 AJAX 请求
        document.addEventListener('DOMContentLoaded', function() {
            fetchData('line', '/test/table', 'mainLineChart');
            fetchData('bar', '/test/pillar', 'mainBarChart');
            fetchData('pie', '/test/fanshaped', 'mainPieChart');
        });
    </script>
</head>
<body>
    <!-- 折线图容器 -->
    <div id="mainLineChart" style="width: 600px;height:400px;"></div>
    <!-- 柱状图容器 -->
    <div id="mainBarChart" style="width: 600px;height:400px;"></div>
    <!-- 扇形图容器 -->
    <div id="mainPieChart" style="width: 600px;height:400px;"></div>
</body>
</html>